package com.smart.primary.util.creat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintStream;
import java.sql.*;
import java.util.*;

public class DatabaseUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(DatabaseUtil.class);

    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    //private static final String[] arr={"id","remarks","update_time","create_time","del_flag"};
    private static final String[] arr={};

    private static final String SQL = "SELECT * FROM ";// 数据库操作

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            LOGGER.error("can not load jdbc driver", e);
        }
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            LOGGER.error("get connection failure", e);
        }
        return conn;
    }

    /**
     * 关闭数据库连接
     * @param conn
     */
    public static void closeConnection(Connection conn) {
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                LOGGER.error("close connection failure", e);
            }
        }
    }

    public static Map getCommentByTableName(List tableName) throws Exception {

        Map map = new HashMap();

        Connection conn = getConnection();

        Statement stmt = (Statement) conn.createStatement();

        for (int i = 0; i < tableName.size(); i++) {
            String table = (String) tableName.get(i);
            ResultSet rs = stmt.executeQuery("SHOW CREATE TABLE " + table);

            if (rs != null && rs.next()) {
                String createDDL = rs.getString(2);
                String comment = parse(createDDL);
                map.put(table, comment);
            }
            rs.close();
        }
        stmt.close();
        conn.close();
        return map;

    }

    /**
     * 获取数据库下的所有表名
     */
    public static List<String> getTableNames() {
        List<String> tableNames = new ArrayList();
        Connection conn = getConnection();
        ResultSet rs = null;
        try {
            //获取数据库的元数据
            DatabaseMetaData db = conn.getMetaData();
            //从元数据中获取到所有的表名
            rs = db.getTables(null, null, null, new String[] { "TABLE" });

            while(rs.next()) {

                tableNames.add(rs.getString(3) );

            }

        } catch (SQLException e) {
            LOGGER.error("getTableNames failure", e);
        } finally {
            try {
                rs.close();
                closeConnection(conn);
            } catch (SQLException e) {
                LOGGER.error("close ResultSet failure", e);
            }
        }
        return tableNames;
    }





    /**
     * @param tableName
     * @return
     */
    public static Map<String,String> getColumnComments(String tableName) {
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        Map<String,String> columnComments = new HashMap<String, String>();//列名注释集合
        ResultSet rs = null;
        try {
            pStemt = conn.prepareStatement(tableSql);
            rs = pStemt.executeQuery("show full columns from " + tableName);
            ResultSetMetaData metaData = pStemt.getMetaData();
            int i = 1 ;
            while (rs.next()) {
                int size=metaData.getColumnDisplaySize(i);
                if(!useList(arr, rs.getString("Field"))){
                    String name= metaData.getColumnName(i );
                    String type= metaData.getColumnClassName(i );
                    if("Timestamp".equals(type.substring(type.lastIndexOf(".") + 1))){
                        System.out.println("\tprivate Date\t" + StrUtil.removeLine(name) + ";\t\t//" + rs.getString("Comment") + ",字段长度"+size);
                    }else {
                        System.out.println("\tprivate " + type.substring(type.lastIndexOf(".") + 1) + "\t" + StrUtil.removeLine(name) + ";\t\t//" + rs.getString("Comment") + ",字段长度"+size);
                    }
                }
                i ++;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnComments close ResultSet and connection failure", e);
                }
            }
        }
        return columnComments;
    }

    public static boolean useList(String[] arr,String targetValue){
        return Arrays.asList(arr).contains(targetValue);
    }

    public static String parse(String all) {

        String comment = null;

        int index = all.indexOf("COMMENT='");

        if (index < 0) {

            return "";

        }

        comment = all.substring(index + 9);

        comment = comment.substring(0, comment.length() - 1);

        return comment;

    }


    public static void creat(List<String> tableNames) {
        try {
            Map<String,String> m=getCommentByTableName(tableNames);
            PrintStream ps;
            for (String tableName : tableNames) {
                ps = new PrintStream(Creat.getPath(Creat.vo)+StrUtil.toUpperOne(StrUtil.removeLine(tableName))+".java");
                System.setOut(ps);//把创建的打印输出流赋给系统。即系统下次向 ps输出
                getVo(m.get(tableName),tableName);//输出的内容
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void getVo(String comment,String tableName){
        System.out.println("package "+Creat.pack+"."+Creat.vo+";\r\n\r\n" +
                "/**\r\n" +
                " * "+comment+"\r\n" +
                " */");
        System.out.println("public class "+StrUtil.toUpperOne(StrUtil.removeLine(tableName))+"  {");
        getColumnComments(tableName);
        System.out.println("}");

    }

    public static void main(String[] args) throws Exception{
        List<String> tableNames = getTableNames();
        Map m=getCommentByTableName(tableNames);
       for (String tableName : tableNames) {
           System.out.println("//"+m.get(tableName));
           System.out.println("public class "+StrUtil.toUpperOne(StrUtil.removeLine(tableName))+"  {");
           getColumnComments(tableName);
           System.out.println("}");
       }
    }
}